/**
 * 表单方法
 */
var option = {
	elem: '#menu',
	data: [],
}
var menu = new function() {
	this.render = function(opt) {
		$.extend(option, opt)
	}
	this.loadMenu = function(treeData) {
		treeData = treeData || option.data;
		$(option.elem).html('');
		var menu = '';
		var subMenu = '';
		treeData.forEach(item => {
			if (item.children && item.children.length > 0) {
				subMenu = '<ul class="nav nav-subnav">'
				item.children.forEach(item => {
					var subItem = `<li> <a class="page" href="javascript:void(0);" data-url=${item.url}>${item.title}</a> </li>`
					subMenu += subItem
				})
				subMenu += '</ul>'
			}
			menu = `
					<li class="nav-item nav-item-has-subnav">
						<a href="javascript:void(0)">
							<i class="${item.icon}"></i>
							<span>${item.title}</span>
						</a>
						${subMenu}
					 </li>
				`
			$(option.elem).append(menu)
		})
	}

	this.click = function(clickEvent) {
		// 展开目录
		$(document).on('click', '.nav-item-has-subnav > a', function() {
			var $subnavToggle = $(this);
			var $navHasSubnav = $subnavToggle.parent();
			var $subnav = $navHasSubnav.find('.nav-subnav').first();
			$navHasSubnav.siblings().find('.nav-subnav:visible').slideUp(500).parent().removeClass('open');
			$subnav.stop().slideToggle(300, function() {
				$navHasSubnav.toggleClass('open');
			});
		});
		// 菜单选中
		$(document).on('click', '.nav-item a.page', function() {
			clickEvent($(this).data("url"), $(this).text());
		});
	}


	this.activeMenu = function(url) {
		var res = {};
		var $menuItem = $(`${option.elem} a.page[data-url='${url}']`);
		if ($menuItem.length > 0) {
			$('.nav-item').removeClass('active');
			$('.nav-subnav li').removeClass('active');
			$menuItem.parent('li').addClass('active');
			$menuItem.parents('.nav-item-has-subnav').siblings().find('.nav-subnav:visible').slideUp(500).parent().removeClass('open');
			$menuItem.parents('.nav-item-has-subnav').addClass('open').first().addClass('active');
			var $pmenuitem = $menuItem.parents('.nav-item-has-subnav').children("a")

			return {
				url: $menuItem.data("url"),
				title: $menuItem.text(),
				purl: $pmenuitem.data("url"),
				ptitle: $pmenuitem.children("span").text()
			}
		}
		return null;
	}

	this.menuDetail = function(url) {
		var $menuItem = $(`${option.elem} a.page[data-url='${url}']`);
		if ($menuItem.length > 0) {
			var $pmenuitem = $menuItem.parents('.nav-item-has-subnav').children("a")
			return {
				url: $menuItem.data("url"),
				title: $menuItem.text(),
				purl: $pmenuitem.data("url"),
				ptitle: $pmenuitem.children("span").text()
			}
		}
		return null;
	}
}

export default menu;